package com.yj.timecapsule.websocket.interceptor;

import com.yj.timecapsule.common.constant.JwtKey;
import com.yj.timecapsule.common.context.LoginUserContext;
import com.yj.timecapsule.common.enums.ErrorCode;
import com.yj.timecapsule.common.error.BusinessException;
import com.yj.timecapsule.common.utils.JwtUtil;
import com.yj.timecapsule.common.utils.RedisUtil;
import com.yj.timecapsule.entity.user.Users;
import com.yj.timecapsule.entity.user.vo.UserLoginVo;
import com.yj.timecapsule.mapper.UsersMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @author Sean
 * @CreateTime 2024-08-01  21:38
 * @Description
 * @Version 1.0
 */
@Component
@Slf4j
public class WebSocketInterceptor implements HandshakeInterceptor {
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, org.springframework.web.socket.WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest servletRequest){
            String token = servletRequest.getServletRequest().getHeader("token");
            if (token == null || token.isEmpty()) {
                log.info("token为空，请求被拦截");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return false;
            }
            try {
                String tokenForRedis = (String) redisUtil.get(token);
                log.info("从redis中获取到token:{}",tokenForRedis);
                if (tokenForRedis == null){
                    log.info("redis中token为空,用户未登录");
                    throw new BusinessException(ErrorCode.USER_NOT_LOGIN);
                }
            }catch (Exception e){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return false;
            }
            try {
                Claims claims = JwtUtil.parse(JwtKey.SECRET_KEY, token);
                log.info("获取会员登录token：{}", token);
                Long userId = Long.valueOf(claims.get("userId").toString());
                Users users = usersMapper.selectByPrimaryKey(userId);
                UserLoginVo loginVo = new UserLoginVo();
                BeanUtils.copyProperties(users, loginVo);
                loginVo.setToken(token);
                LoginUserContext.setUser(loginVo);
                attributes.put("userId", loginVo.getId());
                log.info("当前登录会员：{}", loginVo);
                return true;
            } catch (Exception e) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return false;
            }

        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }


}
